// 直接用平面欧氏距离（适合短距离场景）

type coord = [number, number];

// 计算欧氏距离
function distance(p1: coord, p2: coord): number {
  const dx = p2[0] - p1[0];
  const dy = p2[1] - p1[1];
  return Math.sqrt(dx * dx + dy * dy);
}

// 线性插值，返回目标距离对应的经纬度
function interpolate(p1: coord, p2: coord, d1: number, d2: number, targetD: number): coord {
  const ratio = (targetD - d1) / (d2 - d1);
  return [
    p1[0] + (p2[0] - p1[0]) * ratio,
    p1[1] + (p2[1] - p1[1]) * ratio
  ];
}

// 主函数：获取第m段的起止点
export function getSegmentPoints(coords: coord[], n: number, m: number): { start: coord; end: coord } {
  // 1. 计算每段长度和累计长度
  const dists: number[] = [];
  const cumDists: number[] = [0];
  for(let i = 0; i < coords.length - 1; i++) {
    const d = distance(coords[i], coords[i+1]);
    dists.push(d);
    cumDists.push(cumDists[cumDists.length-1] + d);
  }
  const totalLen = cumDists[cumDists.length-1];
  if(n < 1 || m < 1 || m > n) throw new Error('参数 n/m 有误');

  const segLen = totalLen / n;
  const startDist = segLen * (m - 1);
  const endDist = segLen * m;

  // 2. 计算目标点在哪一段，用插值算出经纬度
  function findPoint(targetDist: number): coord {
    for(let i = 0; i < cumDists.length - 1; i++) {
      if(targetDist >= cumDists[i] && targetDist <= cumDists[i+1]) {
        return interpolate(coords[i], coords[i+1], cumDists[i], cumDists[i+1], targetDist);
      }
    }
    return coords[coords.length-1];
  }

  const startPoint = findPoint(startDist);
  const endPoint = findPoint(endDist);
  return { start: startPoint, end: endPoint };
}

// 示例数据
// const coords = [
//   [117.19878533033092, 36.98473913195118],
//   [117.19878533658577, 36.984684883365375],
//   [117.19889293629012, 36.984684308332845],
//   [117.19889065847654, 36.98479803691687]
// ];

// const n = 5; // 分成5段
// const m = 2; // 第2段

// const { start, end } = getSegmentPoints(coords, n, m);
// console.log(`第${m}段起点:`, start);
// console.log(`第${m}段终点:`, end);